import React, { useState, useRef, useEffect } from 'react';
import classNames from 'classnames';
import './index.less';

export interface FabPattern {
  color?: string;
  selectedColor?: string;
  backgroundColor?: string;
  buttonColor?: string;
}

export interface FabContent {
  iconPath?: string;
  selectedIconPath?: string;
  text: string;
  active?: boolean;
}

export interface FabProps {
  /** 可选样式配置项 */
  pattern?: FabPattern;
  /** 水平对齐方式 */
  horizontal?: 'left' | 'right';
  /** 垂直对齐方式 */
  vertical?: 'top' | 'bottom';
  /** 展开菜单显示方式 */
  direction?: 'horizontal' | 'vertical';
  /** 展开菜单内容配置项 */
  content?: FabContent[];
  /** 是否显示 */
  visible?: boolean;
  /** 默认是否展开 */
  defaultExpanded?: boolean;
  /** 是否隐藏主按钮，常态化显示菜单 */
  alwaysExpanded?: boolean;
  /** 展开菜单点击事件 */
  onTrigger?: (item: FabContent, index: number) => void;
  /** 悬浮按钮点击事件 */
  onFabClick?: () => void;
}

const defaultPattern: FabPattern = {
  color: '#3c3e49',
  selectedColor: '#007AFF',
  backgroundColor: '#ffffff',
  buttonColor: '#3c3e49',
};

const Fab: React.FC<FabProps> = ({
  pattern = defaultPattern,
  horizontal = 'left',
  vertical = 'bottom',
  direction = 'horizontal',
  content = [],
  visible = true,
  defaultExpanded = false,
  alwaysExpanded = false,
  onTrigger,
  onFabClick,
}) => {
  const [isExpanded, setIsExpanded] = useState(alwaysExpanded || defaultExpanded);
  const fabRef = useRef<HTMLDivElement>(null);

  const mergedPattern = { ...defaultPattern, ...pattern };

  // 点击外部关闭菜单（仅在非常态化显示时生效）
  useEffect(() => {
    if (alwaysExpanded) return;
    
    const handleClickOutside = (event: MouseEvent) => {
      if (fabRef.current && !fabRef.current.contains(event.target as Node)) {
        setIsExpanded(false);
      }
    };

    if (isExpanded) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isExpanded, alwaysExpanded]);

  const handleFabClick = () => {
    if (content.length > 0 && !alwaysExpanded) {
      setIsExpanded(!isExpanded);
    }
    onFabClick?.();
  };

  const handleItemClick = (item: FabContent, index: number) => {
    onTrigger?.(item, index);
  };

  if (!visible) {
    return null;
  }

  const fabClassName = classNames('fab-container', {
    [`fab-${horizontal}`]: true,
    [`fab-${vertical}`]: true,
    'fab-expanded': isExpanded,
  });

  const menuClassName = classNames('fab-menu', {
    [`fab-menu-${direction}`]: true,
    [`fab-menu-${horizontal}`]: true,
    [`fab-menu-${vertical}`]: true,
    'fab-menu-expanded': isExpanded,
  });

  return (
    <div ref={fabRef} className={fabClassName}>
      {/* 菜单项 */}
      {content.length > 0 && (
        <div className={menuClassName}>
          {content.map((item, index) => (
            <div
              key={index}
              className={classNames('fab-menu-item', {
                'fab-menu-item-active': item.active,
              })}
              onClick={() => handleItemClick(item, index)}
              style={{
                backgroundColor: item.active
                  ? mergedPattern.selectedColor
                  : mergedPattern.backgroundColor,
                color: item.active
                  ? mergedPattern.backgroundColor
                  : mergedPattern.color,
              }}
            >
              {item.iconPath && (
                <img
                  src={item.active && item.selectedIconPath ? item.selectedIconPath : item.iconPath}
                  alt={item.text}
                  className="fab-menu-item-icon"
                />
              )}
              <span className="fab-menu-item-text">{item.text}</span>
            </div>
          ))}
        </div>
      )}

      {/* 主按钮 - 仅在非常态化显示时显示 */}
      {!alwaysExpanded && (
        <div
          className="fab-button"
          onClick={handleFabClick}
          style={{
            backgroundColor: mergedPattern.buttonColor,
          }}
        >
          <div className={classNames('fab-icon', { 'fab-icon-expanded': isExpanded })}>
            {isExpanded ? '×' : '+'}
          </div>
        </div>
      )}
    </div>
  );
};

export default Fab;